from rest_framework import permissions, filters, response, status
from apps.api.function.models import FunctionModel
from apps.api.function.serializers import FunctionModelSerializer
from apps.api.project.models import ProjectModel
from utils import viewsets
from utils.response import data_response


class FunctionViewSet(viewsets.MyViewSets):
    queryset = FunctionModel.objects.all()
    serializer_class = FunctionModelSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [filters.OrderingFilter]
    ordering_fields = ['create_time']

    def list(self, request, *args, **kwargs):
        keyword = request.query_params.get("project")
        if keyword != '':
            projs_id = ProjectModel.objects.filter(name__icontains=keyword).values("id")
            qs = self.get_queryset().filter(project__in=projs_id).order_by("-create_time")
        else:
            qs = self.get_queryset().order_by("-create_time")

        page = self.paginate_queryset(qs)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            page_data = self.get_paginated_response(serializer.data)
            # for result in page_data.data["results"]:
            #     result["is_superuser"] = "管理员" if result["is_superuser"] == 1 else "普通用户"
            result = data_response(data=page_data.data)
            return response.Response(result, status=status.HTTP_200_OK)

        serializer = self.get_serializer(qs, many=True)
        result = data_response(data=serializer.data)
        return response.Response(result, status=status.HTTP_200_OK)
